package com.github.permissiondog.cancanpbackend.servlet;

import com.github.permissiondog.cancanpbackend.model.User;
import com.github.permissiondog.cancanpbackend.request.LoginRequest;
import com.github.permissiondog.cancanpbackend.response.UserResponse;
import com.github.permissiondog.cancanpbackend.service.UserService;

import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends BaseServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        LoginRequest r = bind(request, response, LoginRequest.class);
        if (r == null) {
            return;
        }

        User u = UserService.getInstance().login(r.username, r.password);
        if (u == null) {
            json(response, UserResponse.builder().ok(false).msg("用户名或密码错误").build());
            return;
        }

        // 将登录的用户 ID 写入到会话
        request.getSession().setAttribute("uid", u.getId());
        log("登录: " + u.getId());

        json(response, UserResponse.builder().ok(true).user(u).build());
    }



}
